package cn.ymjr.sys.util;

import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.*;

/**
 * Created by tiny on 2018/9/26.
 */
public class PayCommonUtil {
    private static final Logger logger = Logger.getLogger(PayCommonUtil.class);
    public static final String API_KEY = "SJQR5oKI1cQHBXdKx79cgaMzgVk2IetI";

    //随机字符串生成
     public static String getRandomString(int length) {
         //length表示生成字符串的长度
         String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         Random random = new Random();
         StringBuffer sb = new StringBuffer();
         for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
         }
    //组装xml
    public static String getRequestXml(SortedMap<String,Object> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String key = (String)entry.getKey();
            String value = (String)entry.getValue();
            //||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)
            if ("attach".equalsIgnoreCase(key) ||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {
                sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");
            }else {
                sb.append("<"+key+">"+value+"</"+key+">");
                 }
            }
        sb.append("</xml>");
        return sb.toString();
     }
    //生成签名
     public static String createSign(SortedMap<String,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
         logger.info(sb.toString());
        String sign = MD5Util.encode(sb.toString()).toUpperCase();
        return sign;
    }
    //请求方法
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
         try {
             URL url = new URL(requestUrl);
             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
             conn.setDoOutput(true);
             conn.setDoInput(true);
             conn.setUseCaches(false);
             // 设置请求方式（GET/POST）
             conn.setRequestMethod(requestMethod);
             conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
             // 当outputStr不为null时向输出流写数据
             if (null != outputStr) {
                 OutputStream outputStream = conn.getOutputStream();	                // 注意编码格式
                 outputStream.write(outputStr.getBytes("UTF-8"));
                 outputStream.close();
             }
             // 从输入流读取返回内容
             InputStream inputStream = conn.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
             String str = null;
             StringBuffer buffer = new StringBuffer();
             while ((str = bufferedReader.readLine()) != null) {
                 buffer.append(str);
             }
             // 释放资源
             bufferedReader.close();
             inputStreamReader.close();
             inputStream.close();
             inputStream = null;
             conn.disconnect();
             return buffer.toString();
         } catch (ConnectException ce) {
             logger.info("连接超时：{}"+ ce);
         } catch (Exception e) {
             logger.info("https请求异常：{}"+ e);
         }
         return null;
     }

    //xml解析
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
         strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
         if(null == strxml || "".equals(strxml)) {
             return null;
         }
         Map m = new HashMap();
         InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
         SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element rootElement = doc.getRootElement();
        List list = rootElement.getChildren();
         Iterator it = list.iterator();
         while(it.hasNext()) {
             Element e = (Element) it.next();
             String k = e.getName();
             String v = "";
             List children = e.getChildren();
             if(children.isEmpty()) {
                 v = e.getTextNormalize();
             } else {
                 v = getChildrenText(children);
             }
             m.put(k, v);
         }
         //关闭流
        in.close();
         return m;
     }
    public static String getChildrenText(List children) {
         StringBuffer sb = new StringBuffer();
         if(!children.isEmpty()) {
             Iterator it = children.iterator();
             while(it.hasNext()) {
                 Element e = (Element) it.next();
                 String name = e.getName();
                 String value = e.getTextNormalize();
                 List list = e.getChildren();
                 sb.append("<" + name + ">");
                 if(!list.isEmpty()) {
                     sb.append(getChildrenText(list));
                 }
                 sb.append(value);
                 sb.append("</" + name + ">");
             }
         }
         return sb.toString();
     }

}
